import json
import datetime


#得到消息的json文件的部分

#得到单个数据请求的数据区长度
def get_msg_len(a):
    msg_len_bytes=a[1:5]
    msg_len=int(str(msg_len_bytes,encoding="ascii"))
    return msg_len

#得到数据区的json文件的部分
def get_package_body(a):

    head_signal=False
    tail_signal=False
    info=bytearray(0)
    for i in a:
        if i==40:
            #print("找到数据包包头，开始解析数据>>>>>>>>>")
            head_signal=True
            #info.append(i)
            #continue
        if head_signal==True:
            info.append(i)
        if i==41:
            #print("找到数据包包尾，返回完整数据包>>>>>>>>>")
            tail_signal=True
            #info.append(i)
            #continue
        if head_signal and tail_signal:
            break
    #print(info)
    msg_len = get_msg_len(info)
    #print(msg_len)
    assert info.__len__()==msg_len+7
    #print("数据长度校验通过》》》")
    #print(bytes(info))
    return str(bytes(info)[5:5+msg_len],encoding="utf-8")

#得到json文件的value通过key值
def get_json_str__value(json_dir,key):
    json_dic = json.loads(json_dir)
    #print(j)
    #print(type(j))
    value=json_dic[key]
    #print(image_path)
    #if json_dic.has_key(key):
    return value

def get_package_json_value_by_key(packages_bytes,key):
    json_str = get_package_body(packages_bytes)
    #print(json_str)
    return get_json_str__value(json_str,key)



def get_identify_box_list(result):
    #
    #print(type(size[0]))

    box_num = int(result.__len__() / 32)

    for i in range(box_num):
        identifyBox = []
        sub_result = result[i * 32:i * 32 + 32]
        left_cord_y=int(sub_result[8:12])
        left_cord_x = int(sub_result[12:16])
        right_cord_y=int(sub_result[16:20])
        right_cord_x = int(sub_result[20:24])

        #print((sub_result[24:28]))
        image_width_pixel =int(sub_result[24:28])

        image_hight_pixel = int(sub_result[28:32])
        pixel_width=right_cord_x-left_cord_x
        pixel_hight=right_cord_y-left_cord_y
        percentage_leftX = int((left_cord_x / image_width_pixel) * 1000)
        percentage_leftY = int((left_cord_y / image_hight_pixel) * 1000)
        percentage_width = int((pixel_width/ image_width_pixel) * 1000)
        percentage_hight = int((pixel_hight/ image_hight_pixel) * 1000)
        box_dic ={
                     "classifyResult": sub_result[0:4],
                     "confidence": float(sub_result[4:8]),
                     "leftX": percentage_leftX,
                     "leftY": percentage_leftY,
                     "xLength": percentage_width,
                     "yLength": percentage_hight
                 }
        identifyBox.append(box_dic)
        # print(box_dic)
        #print(identifyBox)
        identify={
                 "modelId":1,
                 "identifyBox":identifyBox}
    return identify

#把裁剪图片识别得到的参数值转换为全图的比例值
def trans_crop_box_params(image_size,crop_image_cord,result):
    result_all=""
    box_num = int(result.__len__() / 32)
    for i in range(box_num):
        sub_result = result[i * 32:i * 32 + 32]
        left_cord_y=int(sub_result[8:12])
        trans_left_cord_y = left_cord_y + crop_image_cord[1]
        left_cord_x = int(sub_result[12:16])
        trans_left_cord_x = left_cord_x + crop_image_cord[0]
        right_cord_y=int(sub_result[16:20])
        trans_right_cord_y = right_cord_y + crop_image_cord[1]
        right_cord_x = int(sub_result[20:24])
        trans_right_cord_x = right_cord_x + crop_image_cord[0]
        trans_sub_result=sub_result[0:8]+str(trans_left_cord_y).rjust(4, '0')+str(trans_left_cord_x).rjust(4, '0')+str(trans_right_cord_y).rjust(4, '0')+str(trans_right_cord_x).rjust(4, '0')+str(image_size[0]).rjust(4, '0')+str(image_size[1]).rjust(4, '0')
        result_all+=trans_sub_result
    return result_all


def get_identify_dic_by_result_dic(server_result_dic):
    identify_list= []
    for model_id,result in server_result_dic.items():
        box_num = int(result.__len__() / 32)
        identifyBox = []
        for i in range(box_num):
            sub_result = result[i * 32:i * 32 + 32]
            left_cord_y=int(sub_result[8:12])
            left_cord_x = int(sub_result[12:16])
            right_cord_y=int(sub_result[16:20])
            right_cord_x = int(sub_result[20:24])
            image_width_pixel =int(sub_result[24:28])
            image_hight_pixel = int(sub_result[28:32])
            pixel_width=right_cord_x-left_cord_x
            pixel_hight=right_cord_y-left_cord_y
            percentage_leftX = int((left_cord_x / image_width_pixel) * 1000)
            percentage_leftY = int((left_cord_y / image_hight_pixel) * 1000)
            percentage_width = int((pixel_width/ image_width_pixel) * 1000)
            percentage_hight = int((pixel_hight/ image_hight_pixel) * 1000)
            box_dic ={
                         "classifyResult": sub_result[0:4],
                         "confidence": float(sub_result[4:8]),
                         "leftX": percentage_leftX,
                         "leftY": percentage_leftY,
                         "xLength": percentage_width,
                         "yLength": percentage_hight
                     }
            identifyBox.append(box_dic)
        # print(box_dic)
        #print(identifyBox)
        identify={
                     "modelId":model_id,
                     "identifyBox":identifyBox}
    identify_list.append(identify)
    return identify_list


def generate_package_hz(request_dic,server_result_dic):
    return_msg = get_json_message_hz(request_dic, server_result_dic)

    STX = b'\x28'  # 帧开头
    json_info = json.dumps(return_msg)
    #print(json_info)

    MSG = bytes(json_info, encoding="utf-8")  # 消息区、
    msg_len_str = MSG.__len__()

    msg_len_str_std = str(msg_len_str).rjust(4, '0')
    # print(msg_len_str_std)
    MSG_LEN = bytes(msg_len_str_std, encoding="ascii")

    CHK = b'\x00'
    ETX = b'\x29'  # 帧结尾
    PACKAGE = STX + MSG_LEN + MSG + CHK + ETX
    return PACKAGE

def get_json_message_hz(request_dic, server_result_dic):
    identify = get_identify_dic_by_result_dic(server_result_dic)
    json_msg = {
        "imagePath": request_dic["image"],

        "taskId":request_dic["taskId"],
        "camera":request_dic["camera"],

        "identify": identify
    }
    # ("json_msg")
    # print(json_msg)
    return json_msg


def get_json_message(request_dic,server_result_dic):
        identify=get_identify_dic_by_result_dic(server_result_dic)
        json_msg = {
                    "imagePath": request_dic["image_path"],
                    "command": 1,
                    "state": 1,
                    "repostNum": 1,
                    "messageId": request_dic["message_id"],
                    "ipcId": request_dic["ipc_id"],
                    "isReTake": 0,
                    "identifyNum": 1,
                    "identify": identify
                    }
        #("json_msg")
        #print(json_msg)
        return json_msg

def get_yjjy_list_by_result_dic(identify_list,model_id):
    identify = {
        "modelId": model_id,
        "identifyResult": identify_list}
    return identify

def get_json_message_yjjy(request_dic, identify_list,model_id):
    identify = get_yjjy_list_by_result_dic(identify_list,model_id)
    json_msg = {
        "imagePath": request_dic["image_path"],
        "command": 1,
        "state": 1,
        "repostNum": 1,
        "messageId": request_dic["message_id"],
        "ipcId": request_dic["ipc_id"],
        "isReTake": 0,
        "identifyNum": 1,
        "identify": [identify]
    }
    # ("json_msg")
    # print(json_msg)
    return json_msg


def generate_package_by_result_list(request_dic,result_list):
    return_msg = get_json_message(request_dic, result_list)

    STX = b'\x28'  # 帧开头
    json_info = json.dumps(return_msg)
    #print(json_info)

    MSG = bytes(json_info, encoding="utf-8")  # 消息区、
    msg_len_str = MSG.__len__()

    msg_len_str_std = str(msg_len_str).rjust(4, '0')
    # print(msg_len_str_std)
    MSG_LEN = bytes(msg_len_str_std, encoding="ascii")

    CHK = b'\x00'
    ETX = b'\x29'  # 帧结尾
    PACKAGE = STX + MSG_LEN + MSG + CHK + ETX
    return PACKAGE


def generate_package(request_dic,server_result_dic):
    return_msg = get_json_message(request_dic, server_result_dic)

    STX = b'\x28'  # 帧开头
    json_info = json.dumps(return_msg)
    #print(json_info)

    MSG = bytes(json_info, encoding="utf-8")  # 消息区、
    msg_len_str = MSG.__len__()

    msg_len_str_std = str(msg_len_str).rjust(4, '0')
    # print(msg_len_str_std)
    MSG_LEN = bytes(msg_len_str_std, encoding="ascii")

    CHK = b'\x00'
    ETX = b'\x29'  # 帧结尾
    PACKAGE = STX + MSG_LEN + MSG + CHK + ETX
    return PACKAGE

#越界经营数据包
def generate_package_yjjy(request_dic,identify_list,model_id):
    return_msg = get_json_message_yjjy(request_dic, identify_list,model_id)

    STX = b'\x28'  # 帧开头
    json_info = json.dumps(return_msg)
    #print(json_info)

    MSG = bytes(json_info, encoding="utf-8")  # 消息区、
    msg_len_str = MSG.__len__()

    msg_len_str_std = str(msg_len_str).rjust(4, '0')
    # print(msg_len_str_std)
    MSG_LEN = bytes(msg_len_str_std, encoding="ascii")

    CHK = b'\x00'
    ETX = b'\x29'  # 帧结尾
    PACKAGE = STX + MSG_LEN + MSG + CHK + ETX
    return PACKAGE



#只从缓冲区取出一个请求包
def get_one_package(client_socket):
    #starttime = datetime.datetime.now()
    #print(starttime)
    head_signal = False

    tail_signal = False

    info = bytearray(0)

    while True:
        SIGNAL = client_socket.recv(1)
        if SIGNAL[0] == 40:
            #print("find package start symbol>>>>>>>>")
            head_signal = True
        if head_signal == True:
            info.append(SIGNAL[0])
        if SIGNAL[0] == 41:
            #print("find package end symbol>>>>>>>")
            tail_signal = True
        if  tail_signal :
            #print("get single data package>>>>>")
            break
    return info

if __name__ == '__main__':
    a = [45,40, 48, 49, 57, 54, 123, 34, 109, 111, 100,
         101, 108, 78, 117, 109, 34, 58, 49, 44, 34,
         105, 109, 97, 103, 101, 80, 97, 116, 104,
         34, 58, 34, 47, 85, 115, 101, 114, 115, 47,
         121, 101, 121, 109, 47, 119, 111, 114, 107,
         47, 51, 51, 51, 47, 99, 104, 48, 49, 95, 50,
         48, 50, 48, 48, 51, 51, 48, 95, 49, 51, 52,
         56, 52, 48, 95, 84, 95, 53, 56, 52, 52, 48,
         46, 106, 112, 103, 34, 44, 34, 109, 101, 115,
         115, 97, 103, 101, 73, 100, 34, 58, 50, 44,
         34, 109, 111, 100, 101, 108, 34, 58, 91, 123,
         34, 105, 112, 99, 73, 100, 34, 58, 34, 51, 51,
         51, 34, 44, 34, 108, 101, 102, 116, 88, 34, 58,
         49, 48, 44, 34, 108, 101, 102, 116, 89, 34, 58,
         49, 50, 44, 34, 115, 99, 101, 110, 101, 73, 100,
         34, 58, 52, 44, 34, 120, 76, 101, 110, 103, 116,
         104, 34, 58, 56, 50, 44, 34, 121, 76, 101, 110,
         103, 116, 104, 34, 58, 55, 57, 125, 93, 44, 34,
         105, 112, 99, 73, 100, 34, 58, 34, 51, 51, 51,
         34, 125, 0, 41]
    print(">>>>")
    #print(get_package_body(bytes(a)))
    m={}
    m[1]=12312
    m["dsds"]="dasdas"
    print(json.loads((json.dumps(m))))
    #print(str(m))
    print(str([1,2,23,3]))
    for i in range(18):
        print(i)
    print(str("masj").rjust(8, '0'))
    print("23123"[1:3]+"312323"[1:3])
